package com.szrt.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.szrt.dto.PageDTO;
import com.szrt.service.impl.UserServiceImpl;

public class UserController extends HttpServlet {
	
	//调用service
	private UserServiceImpl userService=new UserServiceImpl();
	Map<String, Object> jg=new HashMap<String, Object>();
	
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//跨域访问
		resp.setHeader("Access-Control-Allow-Origin", "*");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		

		String method = req.getParameter("method");
		
		if("findPage".equals(method)){
			
			findPage(req,resp);
			return ;
		}else if("mydel".equals(method)){
			mydel(req,resp);
		}
		
	}

	/**
	 * 删除按钮功能
	 * @param req
	 * @param resp
	 */
	private void mydel(HttpServletRequest req, HttpServletResponse resp) {
		
		String idStr = req.getParameter("idStr");
//		System.out.println();
		String[] delId = idStr.split(",");
		Map<String, Object> jg = userService.del(delId);
		
		//以流的形式写到前台
		PrintWriter writer;
		try {
			writer = resp.getWriter();
			Gson json=new Gson();
			String jsonData = json.toJson(jg);
			writer.write(jsonData);
			System.out.println("将数据写到前端");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
	}

	/**
	 * 分页公功能
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	private void findPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		
		req.setCharacterEncoding("utf-8");
		PageDTO page=new PageDTO();
		String currentPage=req.getParameter("currentPage");
		String pageSide=req.getParameter("pageSide");
		
		page.setCurrentPage(Integer.parseInt(currentPage));
		page.setPageSide(Integer.parseInt(pageSide));
		
		jg = userService.findWitdPage(page);
		
		//以流的形式写到前台
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		Gson json=new Gson();
		String jsonData = json.toJson(jg);
		writer.write(jsonData);
		System.out.println("将数据写到前端");
		
	}

}
